package com.hd.trans.files.adapter

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.PopupWindow
import android.widget.RelativeLayout
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.hd.trans.R
import com.hd.trans.TranslationInterior
import com.hd.trans.binding.visible
import com.hd.trans.databinding.ItemAiAnswerBinding
import com.hd.trans.databinding.ItemAiDefaultBinding
import com.hd.trans.databinding.ItemAiExploreBinding
import com.hd.trans.databinding.ItemAiLoadingBinding
import com.hd.trans.databinding.ItemAiTitleTimeBinding
import com.hd.trans.network.bean.aiChat.AIAnswer
import com.hd.trans.network.bean.aiChat.AIDataType
import com.hd.trans.network.bean.aiChat.TaskStatus
import com.hd.trans.share.AudioTimeFormatUtil
import com.hd.trans.utils.DensityUtils
import com.hd.trans.utils.ScreenUtil
import com.hd.trans.utils.TrackerForTrans
import java.text.SimpleDateFormat
import java.util.Date

/**
 * @Author : HeYan
 * @Time : 2023/4/6 16:15
 * @Description : ⽂件描述
 */
class AIAnswerAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private val mList = ArrayList<AIAnswer>()

    var onQuestionClickListener: ((question: String) -> Unit)? = null

    var onAnswerCopyListener: ((question: String) -> Unit)? = null

    var onAnswerDeleteListener: ((position: Int, item: AIAnswer) -> Unit)? = null

    var onAnswerDeleteAllListener: (() -> Unit)? = null

    fun getData(): ArrayList<AIAnswer> {
        return mList
    }

    fun isContainsAnswer():Boolean{
        return mList.any { it.dataType == AIDataType.ANSWER }
    }

    override fun getItemViewType(position: Int): Int {
        return mList[position].dataType.dataType
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            AIDataType.QUESTION.dataType -> {
                ItemAiAnswerViewHolder(
                    ItemAiAnswerBinding.inflate(LayoutInflater.from(parent.context), parent, false)
                )
            }
            AIDataType.ANSWER.dataType -> {
                ItemAiLoadingViewHolder(
                    ItemAiLoadingBinding.inflate(
                        LayoutInflater.from(parent.context),
                        parent,
                        false
                    )
                )

            }
            AIDataType.TITLE.dataType -> {
                ItemAiTimeViewHolder(
                    ItemAiTitleTimeBinding.inflate(
                        LayoutInflater.from(parent.context),
                        parent,
                        false
                    )
                )
            }
            AIDataType.COMM_TIPS.dataType -> {
                ItemAiDefaultViewHolder(
                    ItemAiDefaultBinding.inflate(
                        LayoutInflater.from(parent.context),
                        parent,
                        false
                    ),
                    onQuestionClickListener
                )

            }
            else -> {
                ItemAiExploreViewHolder(
                    ItemAiExploreBinding.inflate(
                        LayoutInflater.from(parent.context),
                        parent,
                        false
                    ),
                    onQuestionClickListener
                )
            }
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (position >= mList.size) {
            return
        }
        val item = mList[position]
        when (getItemViewType(position)) {
            //提问
            AIDataType.QUESTION.dataType -> {
                (holder as ItemAiAnswerViewHolder).apply {
                    bind(item, position)
                }
            }
            //加载
            AIDataType.ANSWER.dataType -> {
                (holder as ItemAiLoadingViewHolder).apply {
                    bind(item, position)
                }
            }
            //顶部时间
            AIDataType.TITLE.dataType -> {
                (holder as ItemAiTimeViewHolder).apply {
                    bind(item, position)
                }
            }
            //提示选项
            AIDataType.COMM_TIPS.dataType -> {
                (holder as ItemAiDefaultViewHolder).apply {
                    bind(item, position)
                }
            }
            //探索
            AIDataType.EXPLORE_TOP.dataType -> {
                (holder as ItemAiExploreViewHolder).apply {
                    bind(item, position)
                }
            }
        }
    }

    override fun getItemCount(): Int {
        return mList.size
    }

    /**
     * 获取历史列表
     * @return MutableList<String>
     */
    fun getHistoryList(): MutableList<String> {
        val list = mutableListOf<String>()
        if (itemCount > 2) {
            for (i in 2 until itemCount) {
                list.add(mList[i].output)
            }
        }
        return list
    }

    @SuppressLint("NotifyDataSetChanged")
    fun clear() {
        val firstData = mList[0]
        mList.clear()//清空数据
        mList.add(firstData)//保留第一条数据
        notifyDataSetChanged()
    }

    @SuppressLint("NotifyDataSetChanged")
    fun delete(item: AIAnswer) {
        mList.remove(item)
        notifyDataSetChanged()
    }

    @SuppressLint("NotifyDataSetChanged")
    fun delete(position: Int) {
        mList.removeAt(position)
        //notifyDataSetChanged()
        notifyItemRemoved(position)
        notifyItemRangeChanged(position, itemCount)
    }

    @SuppressLint("NotifyDataSetChanged")
    fun update(item: AIAnswer) {
        val index = mList.indexOf(item)
        if (index >= 0) {
            mList[index] = item
        }
        notifyDataSetChanged()
    }

    @SuppressLint("NotifyDataSetChanged")
    fun addAll(list: List<AIAnswer>) {
        mList.clear()
        if (list.isNotEmpty()) {
            mList.addAll(list)
        }
        notifyDataSetChanged()
    }

    @SuppressLint("NotifyDataSetChanged")
    fun add(item: AIAnswer) {
        mList.add(item)
        notifyDataSetChanged()
    }

    @SuppressLint("NotifyDataSetChanged")
    fun onUpdateAnswer(result: AIAnswer) {
        if (mList.size > 0 && mList[itemCount - 1].dataType == AIDataType.ANSWER) {
            mList[itemCount - 1].output = result.output
            mList[itemCount - 1].status = result.status
            notifyDataSetChanged()
        }
    }

    /**
     * 默认加载和回答 item
     * @property binding ItemAiLoadingBinding
     * @property onAnswerCopyListener Function1<[@kotlin.ParameterName] String, Unit>?
     * @constructor
     */
    inner class ItemAiLoadingViewHolder constructor(
        val binding: ItemAiLoadingBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: AIAnswer, position: Int) {
            binding.tvContent.text = item.output
            //设置复制展示
//            val isContain = item.output.contains("AI智能思考中")
            binding.ivMore.visible = item.status == TaskStatus.DONE
            //设置宽度
            val lp = binding.tvContent.layoutParams as RelativeLayout.LayoutParams
            if (item.status == TaskStatus.WAIT){
                lp.width = DensityUtils.dp2px(150f)
            }else{
                lp.width = RelativeLayout.LayoutParams.WRAP_CONTENT
            }
            binding.tvContent.layoutParams = lp

            binding.ivMore.setOnClickListener {
                showPop(binding.ivMore, item, position)
            }
            Glide.with(binding.ivHead.context)
                .load(item.placeholder)
                .apply(
                    RequestOptions.bitmapTransform(CircleCrop()).placeholder(item.placeholder)
                        .error(item.placeholder)
                )
                .into(binding.ivHead)
        }
    }

    /**
     * 提问item
     * @property binding ItemAiAnswerBinding
     * @constructor
     */
    inner class ItemAiAnswerViewHolder constructor(val binding: ItemAiAnswerBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: AIAnswer, position: Int) {
            binding.ivMore.setOnClickListener {
                showPop(binding.ivMore, item, position)
            }
            if (TextUtils.isEmpty(item.headUrl)) {
                Glide.with(binding.ivHead.context)
                    .load(R.mipmap.icon_chat_user_default)
                    .into(binding.ivHead)
            } else {
                Glide.with(binding.ivHead.context)
                    .load(item.headUrl)
                    .apply(
                        RequestOptions.bitmapTransform(CircleCrop())
                            .placeholder(R.mipmap.icon_chat_user_default)
                            .error(R.mipmap.icon_chat_user_default)
                    )
                    .into(binding.ivHead)
            }
            binding.tvContent.text = item.output
            binding.tvCreateTime.text = getTime(item.createTime)
        }

        private fun getTime(time: Long): String {
            val pattern = if(AudioTimeFormatUtil.formatCreateTime2(time)
                != AudioTimeFormatUtil.formatCreateTime2(System.currentTimeMillis())){
                //不是今天
                "yyyy MM月dd日 aHH:mm"
            }else{
                "MM月dd日 aHH:mm"
            }
            val dateTime = Date(time)
            val format = SimpleDateFormat(pattern)
            return format.format(dateTime)
        }
    }

    /**
     * 顶部时间 item
     * @property binding ItemAiTitleTimeBinding
     * @constructor
     */
    inner class ItemAiTimeViewHolder constructor(val binding: ItemAiTitleTimeBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: AIAnswer, position: Int) {
            binding.tvContent.text = item.output
        }
    }

    /**
     * 默认提示选项 item
     * @property binding ItemAiDefaultBinding
     * @property onQuestionClickListener Function1<[@kotlin.ParameterName] String, Unit>?
     * @constructor
     */
    inner class ItemAiDefaultViewHolder constructor(
        val binding: ItemAiDefaultBinding,
        var onQuestionClickListener: ((question: String) -> Unit)? = null,
    ) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: AIAnswer, position: Int) {
            binding.apply {
                //当前暂时这么写，可优化
                tvContent.text = item.output
                if (item.questionList.size > 0)
                    tvQuestion1.text = item.questionList[0]
                if (item.questionList.size > 1)
                    tvQuestion2.text = item.questionList[1]
                if (item.questionList.size > 2)
                    tvQuestion3.text = item.questionList[2]
                tvQuestion1.setOnClickListener {
                    TranslationInterior.getTrackerListener().click(TrackerForTrans.AI_TRANS, "示例问题1")
                    onQuestionClickListener?.invoke(tvQuestion1.text.toString())
                }
                tvQuestion2.setOnClickListener {
                    TranslationInterior.getTrackerListener().click(TrackerForTrans.AI_TRANS, "示例问题2")
                    onQuestionClickListener?.invoke(tvQuestion2.text.toString())
                }
                tvQuestion3.setOnClickListener {
                    TranslationInterior.getTrackerListener().click(TrackerForTrans.AI_TRANS, "示例问题3")
                    onQuestionClickListener?.invoke(tvQuestion3.text.toString())
                }
            }
            Glide.with(binding.ivHead.context)
                .load(item.placeholder)
                .apply(RequestOptions.bitmapTransform(CircleCrop()))
                .into(binding.ivHead)
        }
    }

    /**
     * 探索 item
     * @property binding ItemAiExploreBinding
     * @property onQuestionClickListener Function1<[@kotlin.ParameterName] String, Unit>?
     * @constructor
     */
    inner class ItemAiExploreViewHolder constructor(
        val binding: ItemAiExploreBinding,
        var onQuestionClickListener: ((question: String) -> Unit)? = null,
    ) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: AIAnswer, position: Int) {
            binding.tvTitle.text = item.explore.title
            binding.tvQuestion.text = item.explore.question
            binding.llQuestion.setOnClickListener {
                onQuestionClickListener?.invoke(item.explore.question)
            }
        }
    }


    private var pop: PopupWindow? = null
    private var windowHeight = 0
    private var popupHeight = 0
    private var params: ViewGroup.LayoutParams? = null
    //依附view的高度
    private var viewHeight = 0

    private fun measureHeight(v: View) {
        //测量popupwindow高度
        v.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
        popupHeight = v.measuredHeight //获取测量后的高度
    }

    private fun showPop(view: View, answer: AIAnswer, position: Int) {
        //获取activity的contentview
        val v: View = LayoutInflater.from(view.context).inflate(R.layout.dialog_ai_pop_item, null)
        val cardView = v.findViewById<CardView>(R.id.card_view)
        val llFirst = v.findViewById<View>(R.id.ll_first)
        val llSecond = v.findViewById<View>(R.id.ll_second)
        llFirst.visibility = View.VISIBLE
        llSecond.visibility = View.GONE

        if (params != null) {
            cardView.layoutParams = params
        }

        if (pop == null) {
            pop = PopupWindow(view.context)
            pop!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            pop!!.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
            pop!!.isFocusable = true
            pop!!.isOutsideTouchable = true
            measureHeight(v)
            //顺便也测一下依附控件高度
            view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
            viewHeight = view.measuredHeight
        }

        pop!!.contentView = v

        v.findViewById<View>(R.id.item_copy).setOnClickListener {
            onAnswerCopyListener?.invoke(answer.output)
            pop!!.dismiss()
        }
        v.findViewById<View>(R.id.item_delete).setOnClickListener {
            onAnswerDeleteListener?.invoke(position, answer)
            pop!!.dismiss()
        }
        v.findViewById<View>(R.id.item_delete_all).setOnClickListener {
            cardView.setCardBackgroundColor(view.context.resources.getColor(R.color.color_EB4D3D))
            params = cardView.layoutParams
            params?.width = cardView.width
            params?.height = cardView.height
            cardView.layoutParams = params
            llFirst.visibility = View.GONE
            llSecond.visibility = View.VISIBLE
        }

        llSecond.setOnClickListener {
            onAnswerDeleteAllListener?.invoke()
            pop!!.dismiss()
        }

        //创建长度为2的数组，分别记录指定view在屏幕的x 和 y轴
        val location = IntArray(2)
        // 获得指定view在屏幕的位置
        view.getLocationOnScreen(location)

        //判断view在屏幕Y轴离底部不够一个pop的高度
        if (ScreenUtil.getScreenHeight(view.context) - popupHeight - viewHeight > location[1]) {
            //如果够就显示在底部
            pop!!.showAsDropDown(view)
        } else {
            pop!!.showAtLocation(view, 0,
                location[0], location[1] - popupHeight)
        }
    }

}

